package s.k.gui.webtest.page.resource;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**默认通过get的方法来获得页面的内容，如果页面需要用post来访问需要自己重新编写方法<br>
 * ，一般来说get就足够了
 * */
public class PageResource {
	private HttpClient client= new DefaultHttpClient();;
	private HttpGet httpGet;
	private HttpResponse response;
	private HttpEntity entity;
	/**获取整个url访问的response，可以通过response来进行交互或者下载页面或者对页面进行
	 * @throws IOException 
	 * @throws ClientProtocolException */
	public HttpResponse getResponse(String url) throws ClientProtocolException, IOException{
		try{
			if(response==null){
				/**设置请求超时*/
				client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
				httpGet = new HttpGet(url);
				/**读取超时*/
				client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
				DefaultHttpRequestRetryHandler handler = new DefaultHttpRequestRetryHandler(1,false);
				((AbstractHttpClient)client).setHttpRequestRetryHandler(handler);
				response = client.execute(httpGet);		
				return response;
			}
		}catch(Exception e){			
			System.out.println("访问"+url+"超时,访问失败！");
			e.printStackTrace();
			throw e;
		}
		return response;
	}

	/**判断页面的status是否正常*/
	public boolean isStatusOK(String url){
		try{
			int statusCode = getResponse(url).getStatusLine().getStatusCode();
			if(statusCode==HttpStatus.SC_OK){
				return true;
			}
		}catch(ClientProtocolException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			closeHttpClient();
		}
		return false;
	}
	/**获取页面的内容取放到指定的文件夹
	 * @throws IOException */
	public void downloadPageText(String url,String path){
		try{
			if(getResponse(url).getStatusLine().getStatusCode()==200){
				entity = getResponse(url).getEntity();
				byte[] responseBody = EntityUtils.toByteArray(entity);
				saveToLocal(responseBody,path);	
			}else{
				System.out.println("服务器响应不正常，不能正常访问！");
			}
		}catch(ClientProtocolException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			closeHttpClient();
		}
	}
	/***把数据存到本地的一个工具类*/
	private void saveToLocal(byte[] data,String path){
		try{
			if(new File(path)==null){
				new File(path).createNewFile();
			}
			DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(path)));		
			for(int i=0;i<data.length;i++){
				out.write(data[i]);
			}
			out.flush();
			out.close();
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			closeHttpClient();
		}
	}
	
	/***获取页面中所有的link，返回链接的集合
	 * 借助jsoup类来实现
	 * @throws IOException 
	 * */
	public Set<String> getAllLinks(String url){
		try{
			Set <String> pageLinks = new HashSet<String>();
			Document doc = Jsoup.connect(url).get();
			Elements links = doc.select("a[href]");
			Elements media = doc.select("[src]");
			Elements imports = doc.select("links");
			for(Element src : media){
				if(src.tagName()=="img"){
					pageLinks.add(src.attr("abs:src"));
				}
			}
			for(Element link:links){
				pageLinks.add(link.attr("abs:href"));
			}
			for(Element link: imports){
				pageLinks.add(link.attr("abs:href"));
			}
			return pageLinks;
		}catch(IOException e){
			e.printStackTrace();
			System.out.println("发生IO异常，读取页面信息的时候出现错误！");
		}
		return null;
	}
	
	
	/**
	 *通过给定的URL，来返回String类型的字符串，作为一个工具类来使用，方便操作。
	 * */
	public String getHtmlByUrl(String url){
		String html = null;
		try{
			if(getResponse(url).getStatusLine().getStatusCode()==200){
				entity=getResponse(url).getEntity();
				html = EntityUtils.toString(entity);
				return html;
			}else{
				System.out.println("访问"+url+"没有成功！错误码为："+getResponse(url).getStatusLine().getStatusCode());
			}
		}catch(ClientProtocolException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			System.out.println("访问地址超时！");
			//e.printStackTrace();
		}
		finally{
			closeHttpClient();
		}
		return null;
	}
	
	/**关闭资源*/
	public void closeHttpClient(){
		client.getConnectionManager().shutdown();
	}
	
	/**判断页面中是否有想找的内容
	 * 尽量写出比较多的字符，这样的准确率会比较高，并且判断是碰见相同的字符串就返回true
	 * 
	 * */
	public boolean isExistText(String url,String text){
		String pageContext = getHtmlByUrl(url);
		if(pageContext.contains(text)){
			return true;
		}else{
			System.out.println("没有找到匹配的字符串！");
		}
		return false;
	}
}
